﻿using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Sgr.Utilities;

namespace Sgr.Sms
{
    /// <summary>
    /// 默认短信服务实现
    /// </summary>
    public class DefaultSmsService : ISmsService
    {
        private readonly IEnumerable<ISmsProvider> _smsProviders;
        private readonly ILogger<DefaultSmsService> _logger;
        private readonly SmsOptions _options;

        /// <summary>
        /// 初始化短信服务
        /// </summary>
        /// <param name="smsProviders">短信服务提供者集合</param>
        /// <param name="logger">日志记录器</param>
        /// <param name="options">短信服务配置</param>
        public DefaultSmsService(
            IEnumerable<ISmsProvider> smsProviders,
            ILogger<DefaultSmsService> logger,
            IOptions<SmsOptions> options)
        {
            _smsProviders = smsProviders ?? throw new ArgumentNullException(nameof(smsProviders));
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
            _options = options?.Value ?? throw new ArgumentNullException(nameof(options));
        }

        /// <summary>
        /// 发送短信
        /// </summary>
        public async Task<SmsResult> SendAsync(
            string phoneNumber,
            string message,
            CancellationToken cancellationToken = default)
        {
            try
            {
                // 参数验证
                if (string.IsNullOrWhiteSpace(phoneNumber))
                    return SmsResult.Failure("手机号码不能为空");

                if (!IsValidPhoneNumber(phoneNumber))
                    return SmsResult.Failure("无效的手机号码格式");

                if (string.IsNullOrWhiteSpace(message))
                    return SmsResult.Failure("短信内容不能为空");

                // 获取配置的提供者
                var provider = GetConfiguredProvider();
                if (provider == null)
                {
                    _logger.LogError("未找到配置的短信服务提供者: {Provider}", _options.Provider);
                    return SmsResult.Failure("未找到可用的短信服务提供者");
                }

                _logger.LogInformation(
                    "发送短信: Provider={Provider}, PhoneNumber={PhoneNumber}, MessageLength={MessageLength}",
                    provider.Name,
                    phoneNumber,
                    message.Length);

                var result = await provider.SendAsync(phoneNumber, message, cancellationToken);

                if (!result.Succeeded)
                {
                    _logger.LogWarning(
                        "短信发送失败: Provider={Provider}, PhoneNumber={PhoneNumber}, Error={Error}",
                        provider.Name,
                        phoneNumber,
                        result.Error);
                }

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex,
                    "短信发送发生异常: PhoneNumber={PhoneNumber}, Message={Message}",
                    phoneNumber,
                    message);
                return SmsResult.Failure($"短信发送失败: {ex.Message}");
            }
        }

        private ISmsProvider? GetConfiguredProvider()
        {
            string providerName = _options.Provider;
            // 如果未配置提供者，使用第一个可用的提供者
            if (string.IsNullOrWhiteSpace(providerName))
                providerName = "SGR_SMS_DEFAULT";

            // 查找配置的提供者
            return _smsProviders.FirstOrDefault(p =>
                p.Name.Equals(providerName, StringComparison.OrdinalIgnoreCase));
        }

        private bool IsValidPhoneNumber(string phoneNumber)
        {
            return RegexHelper.IsValidPhoneNumber(phoneNumber);
        }
    }
}